package com.example.searchcenter.article;

import java.util.ArrayList;
import java.util.List;


import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.searchcenter.R;
import com.example.searchcenter.helper.ImageLoader;
import com.example.searchcenter.helper.JSONParser;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import android.widget.ImageView;
import android.widget.TextView;

public class DetailArticle extends Activity {

	TextView title;
	TextView article_id;
	 //TextView sumary;
	TextView detail;
	TextView date;
	ImageView thumbnail;

	public ImageLoader imageLoader;

	public Log log;

	private String id_article;

	// Progress Dialog
	private ProgressDialog pDialog;

	// JSON parser class
	JSONParser jsonParser = new JSONParser();

	// getActionBar (Back)
	private ActionBar actionBar;

	// single product url
	private static final String url_detail_article = "http://tinhnguyen.edu.vn/apis/getArticleDetail";
	private static String url_image = "https://tinhnguyen.edu.vn/public/img/articles/thumbs/";
	
	// JSON Node names
	static final String TAG_SUCCESS = "success";
	static final String TAG_ARTICLE = "articledetail";
	static final String TAG_ID_ARTICLE = "cid";
	static final String TAG_DATE = "date";
	static final String TAG_TITLE = "title";
	static final String TAG_CATEGORYID = "categoryid";
	static final String TAG_TITLEASCII = "titleASCII";
	static final String TAG_AUTHORID = "postedUserId";
	static final String TAG_TAG = "tag";
	static final String TAG_SUMARY = "sumary";
	static final String TAG_DETAILS = "details";
	static final String TAG_SOURCE = "source";
	static final String TAG_THUMBNAILIMAGEURL = "thumbnailImageUrl";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail_article);

		// check version sdk
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}

		// getting article details from intent
		Intent i = getIntent();

		// getting article id (pid) from intent
		id_article = i.getStringExtra(TAG_ID_ARTICLE);

		// Getting complete article details in background thread
		new GetArticleDetails().execute();

		// getActionBar()
		actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setHomeButtonEnabled(true);
		// actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
	}

	/**
	 * Background Async Task to Get complete article details
	 * */
	class GetArticleDetails extends AsyncTask<String, String, String> {
		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(DetailArticle.this);
			pDialog.setMessage("Loading article details. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Getting article details in background thread
		 * */
		protected String doInBackground(String... params) {

			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {

					// Check for success tag
					int success;

					try {

						// Building Parameters
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("id", id_article));

						// getting product details by making HTTP request
						// Note that product details url will use GET request
						JSONObject json = jsonParser.makeHttpRequest(
								url_detail_article, "GET", params);

						// check your log for json response
						Log.d("Article Details", json.toString());

						// json success tag
						success = json.getInt(TAG_SUCCESS);

						// Toast.makeText(getApplicationContext(),params.toString(),
						// Toast.LENGTH_LONG).show();
						if (success == 1) {
							imageLoader = new ImageLoader(
									getApplicationContext());
							// successfully received article details
							JSONArray articleObj = json
									.getJSONArray(TAG_ARTICLE); // JSON Array

							// get first article object from JSON Array
							JSONObject article = articleObj.getJSONObject(0);
							// Toast.makeText(getApplicationContext(),product.toString(),
							// Toast.LENGTH_LONG).show();
							// article with this pid found
							// Edit Text
							title = (TextView) findViewById(R.id.title_article_detail);
							// article_id = (TextView)
							// findViewById(R.id.id_article_detail);
							// sumary = (TextView)
							// findViewById(R.id.sumary_article_detail);
							detail = (TextView) findViewById(R.id.detail_article_detail);
							date = (TextView) findViewById(R.id.createDateArticle);
							thumbnail = (ImageView) findViewById(R.id.imageArticle);

							Log.w("image", TAG_THUMBNAILIMAGEURL);

							// display article data in textview
							title.setText(article.getString(TAG_TITLE));
							// article_id.setText(article.getString(TAG_ID_ARTICLE));
							// sumary.setText(article.getString(TAG_SUMARY));
							detail.setText(article.getString(TAG_DETAILS));
							date.setText(article.getString(TAG_DATE));
							imageLoader.DisplayImage(
									url_image+article.getString(TAG_THUMBNAILIMAGEURL),
									thumbnail);

						} else {
							// not found
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

			});
			return null;

		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once got all details
			pDialog.dismiss();
		}
	}
	/**
	 * set button share into actionbar
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.detail_article_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	/**
	 * On select action bar icon
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		// take appropriate action for each item click
		switch (item.getItemId()) {
		case R.id.action_share_place:
			Intent share = new Intent(android.content.Intent.ACTION_SEND);
			share.setType("text/plain");
			share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			// add data to intent
			share.putExtra(Intent.EXTRA_SUBJECT, "Share to Facebook");
			share.putExtra(Intent.EXTRA_TEXT,
					"http://tinhnguyen.edu.vn/articles/detail/" +  id_article);
			startActivity(Intent.createChooser(share, "Share to Facebook"));
			return true;
		
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
